<?php

function callApi($apiName, $args = array())
{
    //
    $paths = explode('/', $apiName);
    $controllerName = "Api\\Controller\\$paths[0]Controller";
    $controller = new $controllerName();
    $controller->setInternalCallApi();
    $function = $paths[1];
    $method = new ReflectionMethod($controllerName, $function);
    try {
        $method->invokeArgs($controller, $args);
    } catch (Api\Exception\ReturnException $ex) {
        return $ex->getResult();
    }
}

function apiToAjax($result)
{
    $result['status'] = $result['success'];
    $result['info'] = $result['message'];
    unset($result['success']);
    unset($result['message']);
    return $result;
}

function ensureApiSuccess($apiResult)
{
    if (!$apiResult['success']) {
        api_show_error($apiResult['message']);
    }
}

/**
 * 显示错误消息，根据调用方式。如果是ajax调用，则返回ajax错误信息；
 * 如果是直接页面访问的话，直接显示错误消息
 * @param $message
 */
function api_show_error($message, $extra = array())
{
    if (IS_AJAX) {
        api_show_error_json($message, $extra);
    } else {
        api_show_error_html($message, $extra);
    }
}

function api_show_error_json($message, $extra = array())
{
    //生成错误信息
    $json['status'] = false;
    $json['info'] = $message;
    $json = array_merge($json, $extra);

    //返回
    header('Content-Type: application/json');
    echo json_encode($json);
}

function api_show_error_html($message, $extra = null)
{
    class EnsureApiSuccessController extends Think\Controller
    {
        public function showError($message)
        {
            $this->error($message);
        }
    }

    $controller = new EnsureApiSuccessController();
    $controller->showError($message);
}

function handle_exception($exception)
{
    // 显示错误消息
    $message = $exception->getMessage();
    if (method_exists($exception, 'getExtra')) {
        $extra = $exception->getExtra();
    } else {
        $extra = array();
    }
    $extra['error_code'] = $exception->getCode();
    api_show_error($message, $extra);
}

/**
 * @param $url  string  post url
 * @param $cookiepath  string  file path
 * @param $data  array   key-value array
 * @return mixed json
 */
function curl_get($url, $data, $referrer = "http://wjmc126.icare361.com/")
{
    $snoopy = new \Common\Extend\Snoopy;
    $snoopy->agent = "(compatible; MSIE 4.01; MSN 2.5; AOL 4.0; Windows 98)"; //伪装浏览器
    $snoopy->referer = $referrer; //伪装来源页地址 http_referer
    $snoopy->rawheaders["Pragma"] = "no-cache"; //cache 的http头信息   //$snoopy->rawheaders["X_FORWARDED_FOR"] = "127.0.0.101"; //伪装ip
    $snoopy->submit($url, $data);

    return $snoopy->results;

}

/**
 * 登陆远程服务器
 * @param $id
 * @return mixed
 */
function remote_login($id)
{
    $url = "http://wjmc126.icare361.com/api/login";
    $post = array(
        'login_name' => get_username($id),
        'password' => get_table_field($id, 'id', 'password', 'ucenter_member'),
        'group_id' => get_role_id($id),
    );
    $remotData = curl_get($url, $post);
    $remotData = json_decode($remotData, true);
    if($remotData['status']==1) {
        //将北京用户id保存到数据库中
        $bjid = $remotData['data']['id'];
        M('UcenterMember')->save(array('id' => $id, 'bj_id' => $bjid));
    }
    return $remotData;
}

/**
 * 服务器端手动绑定患者功能
 * @param $doctorToken
 * @param $patient_id
 * @return mixed
 */
function remote_bind_doctor($doctorToken, $patient_id)
{

    $url = "http://wjmc126.icare361.com/api/doctor/bind-family-expert-or-doctor";
    $post = array(
        'token' => $doctorToken,
        'patient_id'=>$patient_id
    );
    $remotData = curl_get($url, $post);
    $remotData = json_decode($remotData, true);
    return $remotData;
}

/**
 * 服务器端手动解绑患者
 * @param $doctorToken
 * @param $user_id  本地数据库的userid 内部自行获取远程服务器id
 * @return mixed
 */
function remote_unbind_doctor($doctorToken, $user_id)
{
    $bj_id = get_table_field($user_id, 'id', 'bj_id', 'ucenter_member');
    if (empty($bj_id)) {
        $remoteUserData = remote_login($user_id);
        $bj_id = $remoteUserData['data']['id'];
    }
    $url = "http://wjmc126.icare361.com/api/doctor/unbind-family-expert-or-doctor";
    $post = array(
        'token' => $doctorToken,
        'patient_id'=>$bj_id
    );
    $remotData = curl_get($url, $post);
    $remotData = json_decode($remotData, true);
    return $remotData;
}

// 允许API抛出异常，将异常视为普通的Controller::error();
set_exception_handler('handle_exception');